#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
项目名称: 中青晶彩看点获取分享链接
Author: Fidcz
功能：中青晶彩看点获取分享链接
Date: 2021/12/02 20:00
Update: 2021/12/20 21:19
cron: 50 22 * * ?
new Env('中青晶彩看点获取分享链接');

    中青cookie保存为 export zq_cookies="cookie1:备注1@cookie2:备注2" # 备注可忽略 "cookie1@cookie2"
    晶彩cookie为 jc_cookies,其他同上
"""

import time
# from urllib.parse import urlencode
import requests
import json
import sys, os
import random
import logging

# 使用logger输出
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger(__name__)

def bodyTodict(bodyString):
    """
        把body形式文本转为dict
    """

    temp_split = bodyString.split('&')

    resultDict= {}
    for data in temp_split:
        resultDict[data.split('=')[0]] = data.split('=')[1]
    
    # print(resultDict)
    return resultDict

def getZqCookie():
    """
        获取中青cookie,返回list
    """
    cookieList = []
    if 'zq_cookies' in os.environ:
        cookiesStr = os.environ["zq_cookies"]
        # 使用@分割每个cookie
        cookiesSplit = cookiesStr.split('@')
        for cookie in cookiesSplit:
            if ':' in cookie:
                cookieList.append([cookie.split(':')[0], cookie.split(':')[1]])
            else:
                cookieList.append([cookie.split(':')[0], ''])

    return cookieList

def getJcCookie():
    """
        获取晶彩cookie,返回list
    """
    cookieList = []
    if 'jc_cookies' in os.environ:
        cookiesStr = os.environ["jc_cookies"]
        # 使用@分割每个cookie
        cookiesSplit = cookiesStr.split('@')
        for cookie in cookiesSplit:
            if ':' in cookie:
                cookieList.append([cookie.split(':')[0], cookie.split(':')[1]])
            else:
                cookieList.append([cookie.split(':')[0], ''])

    return cookieList


def getShareUrl(pt:str='zq', cookie:str='', num:int=2) -> list:
    """
        获取分享链接
    """
    if cookie == '' or cookie == None:
        return []
    
    try:
        domain = 'kandian.wkandian.com'
        if pt == 'jc':
            domain = 'ant.xunsl.com'
        shareUrlList = []
        time1 = int(time.time())
        bodyVal = cookie.split('&uid')[0]
        cookie1 = bodyVal.replace('zqkey=', 'cookie=')
        cookie_id = cookie1.replace('zqkey_id=', 'cookie_id=')

        zq_cookie1 = f'{cookie_id}&device_brand=xfdg&device_id=cc7dgdsgfsz83e&device_model=1gx&device_platform=android&device_type=android&inner_version=202107261526&mi=0&openudid=cc7dgdsgfsz83e&os_api=27&os_version=bdftgsdfga&phone_network=WIFI&phone_sim=1&request_time={str(time1)}&time={str(time1-10)}&{bodyVal}'
        
        # 开始获取文章列表
        wzListUrl = f'https://{domain}/WebApi/ArticleTop/listsNewTag'
        wzListHeader = {
            'Host': domain,
            'Referer': f'https://{domain}/h5/20200612makeMoney/?' + zq_cookie1}
        wzListData =  f'{zq_cookie1}&tag=24'
        wzListRespon = requests.post(url=wzListUrl, headers=wzListHeader, data=bodyTodict(wzListData))

        time.sleep(4.5)

        try:
            # 获取随机数
            randomInt = random.randint(0,int(len(wzListRespon.json()['data']['items'])/4))
        except:
            randomInt = 0

        # 开始分享
        for index in range(1, num+1):
            try:
                wzId = wzListRespon.json()['data']['items'][index+randomInt]['id']
                wzShareUrl = wzListRespon.json()['data']['items'][index+randomInt]['share_url']
                wzTitle = wzListRespon.json()['data']['items'][index+randomInt]['title']
                # print('wzId:', wzId, ',title:', wzTitle, '\nurl:', wzShareUrl)

                shareUrl = f'https://{domain}/WebApi/ShareNew/getShareArticleReward'
                shareHeader = {
                                'Content-Type': 'application/x-www-form-urlencoded',
                                'Content-Length': str(len(f'{zq_cookie1}&article_id={wzId}')),
                                'Host': domain,
                                'Referer': f'https://{domain}/h5/20200612makeMoney/?{zq_cookie1}'
                                }
                shareData = f'{zq_cookie1}&article_id={wzId}'
                shareRespon = requests.post(url=shareUrl, headers=shareHeader, data=bodyTodict(shareData))

                if int(shareRespon.json()['status']) == 1:
                    uid = wzShareUrl.split('uid=')[1].split('&')[0]
                    sid = wzShareUrl.split('sid=')[1].split('&')[0]
                    shareTime = int(time.time() * 1000)
                    trueShareUrl = f'{wzShareUrl}&share_id={uid}{sid}{shareTime}&scene_id=fire_share&time={shareTime}'
                    shareUrlList.append([wzTitle, trueShareUrl])
                else:
                    shareUrlList.append([str(wzListRespon.json()['status']), str(wzListRespon.json()['msg'])])
            except Exception as error2:
                shareUrlList.append([f'获取分享链接出错,{repr(error2)}', f'error line:{error2.__traceback__.tb_lineno}'])
                continue
    except Exception as error:
        shareUrlList.append([f'获取分享链接出错,{repr(error)}', f'error line:{error.__traceback__.tb_lineno}'])
    
    return shareUrlList



if __name__ == '__main__':

    zq_cookies = jc_cookies = []
    zq_cookies = getZqCookie()
    jc_cookies = getJcCookie()
    logger.info(f'提供了{len(zq_cookies)}个中青账号')
    logger.info(f'提供了{len(jc_cookies)}个晶彩账号')

    # 首先获取中青分享链接
    logger.info('\n>>>>开始获取中青分享链接<<<<\n')
    for zq_cookie_index in range(len(zq_cookies)):
        # if zq_cookies[zq_cookie_index][1] != '':
        #     cookie = zq_cookies[zq_cookie_index][0]
        #     cookieName = zq_cookies[zq_cookie_index][1]
        # else:
        #     cookie = zq_cookies[zq_cookie_index][0]
        #     cookieName = f'账号{zq_cookie_index+1}'
        
        # print(cookie)
        shareUrlList = getShareUrl('zq', zq_cookies[zq_cookie_index][0])

        logger.info(f'\n\n>>中青账号[{zq_cookie_index+1}:{zq_cookies[zq_cookie_index][1]}] 分享链接如下:')
        for shareUrl in shareUrlList:
            logger.info(f'>{shareUrl[0]}\n{shareUrl[1]}')

    # 获取晶彩分享链接
    logger.info('\n\n>>>>开始获取晶彩分享链接<<<<\n')
    for jc_cookie_index in range(len(jc_cookies)):
        # if zq_cookies[zq_cookie_index][1] != '':
        #     cookie = zq_cookies[zq_cookie_index][0]
        #     cookieName = zq_cookies[zq_cookie_index][1]
        # else:
        #     cookie = zq_cookies[zq_cookie_index][0]
        #     cookieName = f'账号{zq_cookie_index+1}'
        
        # print(cookie)
        shareUrlList = getShareUrl('jc', jc_cookies[jc_cookie_index][0])

        logger.info(f'\n>>晶彩[账号{jc_cookie_index+1}:{jc_cookies[jc_cookie_index][1]}] 分享链接如下:')
        for shareUrl in shareUrlList:
            logger.info(f'>{shareUrl[0]}\n{shareUrl[1]}')

    exit(1)
